/**
 * @(#) ModWorkTimeMediator.as
 *
 * @date		2009. 03. 06.
 * @version		1.0
 * @author		Shin, Yunwoo
 * @description	근무 - Mediator
 * 				근무관리 Presentation Logic을 관리 
 */
package com.skt.common_hr.work_sac.view
{
	import com.skt.common_hr.common.Variables;
	import com.skt.common_hr.common.approval.RequestApprovalMediator;
	import com.skt.common_hr.common.components.CommonAlert;
	import com.skt.common_hr.common.puremvc.CommonMediator;
	import com.skt.common_hr.work_sac.WorkFacade;
	import com.skt.common_hr.work_sac.model.ReqVacationProxy;
	import com.skt.common_hr.work_sac.model.ReqWorkTimeProxy;
	import com.skt.common_hr.work_sac.model.VacationCodeProxy;
	import com.skt.common_hr.work_sac.model.WorkTimeApprovalProxy;
	import com.skt.common_hr.work_sac.model.vo.ReqVacationVO;
	import com.skt.common_hr.work_sac.view.components.ModWorkTimeView;
	import com.wcl.utils.DateUtil;
	import com.wcl.utils.StringUtil;
	
	import flash.events.Event;
	
	import mx.managers.PopUpManager;
	
	import org.puremvc.as3.multicore.interfaces.INotification;
	
	public class ModWorkTimeMediator extends CommonMediator
	{
		public static const NAME:String = "ModWorkTimeMediator"; 

		public var baseDate:Date;	
		public var GWAREKEY:String;
		public var _currentKey:String;
		private var _savingTable:Array;
		
		/**
		* 생성자
		* 
		* @param
		* @return void
		*/
        public function ModWorkTimeMediator( viewComponent:Object )
        {
            super( NAME, viewComponent );
            view.callLater(initView);
        }
 		
		/**
		* View를 초기화 한다.
		*	- View에 기본사항을 출력하고 data를 load
		* @param
		* @return void
		*/
 		private function initView():void
 		{
 			setEventListener();
			// 휴가 코드리스트를 가져온다.
 			var codeProxy:VacationCodeProxy = facade.retrieveProxy(VacationCodeProxy.NAME) as VacationCodeProxy;
			view.worktimeCodeList = codeProxy.worktimeList;
			
 		}
		
		public function exec(date:Date, key:String):void
		{
			bActivated = true;
			baseDate = new Date(date);
			GWAREKEY = key;
			setEventListener();
			loadData();
		}
		
		private function setEventListener():void
		{
 			// 각 버튼들의 Event Handler를 설정하고
 			view.addEventListener(ModWorkTimeView.CONFIRM, onConfirm);
 			view.addEventListener(ModWorkTimeView.DELETE, onDelete);
 			view.addEventListener(ModWorkTimeView.CANCEL, onCancel);
		}
 		
 		private function removeEventListener():void
 		{
 			view.removeEventListener(ModWorkTimeView.CONFIRM, onConfirm);
 			view.removeEventListener(ModWorkTimeView.DELETE, onDelete);
 			view.removeEventListener(ModWorkTimeView.CANCEL, onCancel);
 		}

		private function loadData():void
		{
			var vacProxy:ReqVacationProxy = facade.retrieveProxy(ReqVacationProxy.NAME) as ReqVacationProxy;
			vacProxy.load(GWAREKEY);
		}


  		private function closeView(cancel:Boolean=false):void
  		{
			bActivated = false;
			PopUpManager.removePopUp(view);
			facade.sendNotification((cancel) ? WorkFacade.CANCEL_REQ_WORKTIME:WorkFacade.SUCCEED_REQ_WORKTIME, this);
  		}
 		
 		
		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Process MVC Messages
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
		/**
		* 본 Class에서 처리해야할 Noti들을 등록한다.
		* 
		* @param
		* @return void
		*/
		override public function listNotificationInterests():Array 
		{
			return [
					WorkFacade.LOAD_REQ_VACATION_COMPLETE,
					WorkFacade.LOAD_REQ_VACATION_FAILED,
					WorkFacade.DELETE_REQ_VACATION_COMPLETE,
					WorkFacade.DELETE_REQ_VACATION_FAILED,
					WorkFacade.INSERT_REQ_WORKTIME_COMPLETE,
					WorkFacade.INSERT_REQ_WORKTIME_FAILED,
					RequestApprovalMediator.APPROVAL_CANCEL,
					RequestApprovalMediator.APPROVAL_COMPLETE
					];
		}
		

		/**
		* Noti별로 처리한다.
		* 
		* @param
		* @return void
		*/
		override public function handleNotification(note:INotification):void
		{
			if(bActivated) {
				switch(note.getName()) 
				{
					case WorkFacade.LOAD_REQ_VACATION_COMPLETE:
						view.reqList = (note.getBody() as ReqVacationProxy).reqVacationList;
						if(view.reqList.length>0) {
							view.cause = view.reqList.getItemAt(0).TEXT2;
						}
						break;
					case WorkFacade.INSERT_REQ_WORKTIME_COMPLETE:
						_currentKey = ReqWorkTimeProxy(note.getBody()).outKey; 
						execApproval(_currentKey);
						break;
					case WorkFacade.DELETE_REQ_VACATION_COMPLETE:
						closeView();
						break;
					case WorkFacade.DELETE_REQ_VACATION_FAILED:
					case WorkFacade.INSERT_REQ_VACATION_FAILED:
						CommonAlert.showMessage(commonFacade.bundle, "("+note.getBody().retCode+")"+note.getBody().retText, null, "RFC 오류", view);
						break;
					case RequestApprovalMediator.APPROVAL_COMPLETE:					// 결재 요청  성공
						closeView();
						break;
					case RequestApprovalMediator.APPROVAL_CANCEL:					// 결재 요청 취소
						break;

					case WorkFacade.INSERT_REQ_WORKTIME_FAILED:
						CommonAlert.showMessage(commonFacade.bundle, "("+note.getBody().retCode+")"+note.getBody().retText, null, "RFC 오류", view);
						break;
												
						
					default:
						//trace(this.instanceID+"에서 처리 안된 Noti가 검출됨 : " + note.getBody());
						break;
				}
			}
		}


 		private function onConfirm(event:Event):void
 		{
 			var table:Array = new Array();
 			var i:int = 0;
			var days:Array = ["일", "월", "화", "수", "목", "금", "토"];
 			for each(var src:ReqVacationVO in view.reqList)
 			{
 				if(src.selectedIndex<=0) {
 					CommonAlert.showMessage(commonFacade.bundle, "ALERT_INVALID_WORKTYPE");
 					return;
 				}
 				
 				if(StringUtil.NVL(src.TEXT1) == "") {
 					CommonAlert.showMessage(commonFacade.bundle, "근태 신청 사유를 반드시 입력하여 주십시오.");
 					return;
 				} 
 				
  				var jsonObj:Object = new Object;
 				jsonObj.SEQNO = (i++).toString();
  				jsonObj.AWART = view.worktimeCodeList.getItemAt(src.selectedIndex).code;
 				jsonObj.AWATX = view.worktimeCodeList.getItemAt(src.selectedIndex).text;
 				jsonObj.PERNR = jsonObj.IPERNR = Variables.myPernr;
 				jsonObj.DGBN  = "2";
 				jsonObj.ENDDA = jsonObj.BEGDA = DateUtil.toBasicString(src.BEGDA);
				
 				src.ENDUZ.fullYear = src.BEGUZ.fullYear = src.BEGDA.fullYear;
 				src.ENDUZ.month = src.BEGUZ.month = src.BEGDA.month;
 				src.ENDUZ.date  = src.BEGUZ.date  = src.BEGDA.date;
 				
 				jsonObj.BEGUZ = DateUtil.toBasicTimeString(src.BEGUZ);
 				jsonObj.ENDUZ = DateUtil.toBasicTimeString(src.ENDUZ);

 				// 요일추가
 				jsonObj.BEGDAday = days[src.BEGDA.day];
 				jsonObj.BEGUZday = days[src.BEGUZ.day];
 				if(src.ENDUZ.hours<9) src.ENDUZ.date += 1;
 				jsonObj.ENDUZday = days[src.ENDUZ.day];
 				
 				// 20120423 광현 추가 
 				jsonObj.OT011 = src.OT011; 
				jsonObj.OT012 = src.OT012; 
				jsonObj.OT021 = src.OT021; 
				jsonObj.OT022 = src.OT022; 
//				if(Variables.company == 'SAC') {
//					jsonObj.OT023 = src.OT023;	
//				}
				jsonObj.OT023 = src.OT023;
				
				jsonObj.TEXT1 =src.TEXT1; 
				
				
				/*
 				src.SEQNO = (i++).toString();
 				src.AWART = view.worktimeCodeList.getItemAt(src.selectedIndex).code;
 				src.AWATX = view.worktimeCodeList.getItemAt(src.selectedIndex).text;
 				src.PERNR = src.IPERNR = Variables.myPernr;
 				src.DGBN  = "2";
 				src.ENDDA = new Date(src.BEGDA);
 				if(Number(src.BEGUZ) > Number(src.ENDUZ) ) {
 					CommonAlert.showMessage(commonFacade.bundle, "ALERT_INVALID_TIME");
 					return ;
 				}
 				*/
 				jsonObj.GWAREKEY = GWAREKEY;
 				table.push(jsonObj);
 			}
 			
 			_savingTable = table;
 			saveWorkTime(table);
 		}
		
		private function saveWorkTime(table:Array):void
		{ 		
 			var proxy:ReqWorkTimeProxy = facade.retrieveProxy(ReqWorkTimeProxy.NAME) as ReqWorkTimeProxy;
 			proxy.InsertWorkTime("2", table);
		}
		
 		private function execApproval(key:String):void
 		{
 			var approval:RequestApprovalMediator = facade.retrieveMediator(RequestApprovalMediator.NAME) as RequestApprovalMediator;
 			if(approval==null) {
 				approval = new RequestApprovalMediator(view, "02");
 				facade.registerMediator(approval);
 			}
 			
 			var appProxy:WorkTimeApprovalProxy = facade.retrieveProxy(WorkTimeApprovalProxy.NAME) as WorkTimeApprovalProxy;
 			appProxy.key = key;
 			appProxy.dataProvider = _savingTable;
 			approval.execRequest(view, appProxy);
 		}


 		private function onDelete(event:Event):void
 		{
 			var proxy:ReqWorkTimeProxy = facade.retrieveProxy(ReqWorkTimeProxy.NAME) as ReqWorkTimeProxy;
 			proxy.deleteWorkTime([{GWAREKEY: GWAREKEY}]);
 		}
 		
 		private function onCancel(event:Event):void
 		{
			closeView(true);	
 		}
 		


 		private function onClickAddRecord(event:Event):void
 		{
 			addRecord();
 		}
 		
 		private function onDelRecord(event:Event):void
 		{
			for (var i:int=0; i<view.reqList.length; i++)
			{
				if(view.reqList.getItemAt(i).del) {
					view.reqList.removeItemAt(i--);
				}
			} 			
			if(view.reqList.length==0) {
	 			var vo:ReqVacationVO = new ReqVacationVO();
	 			vo.BEGDA = new Date(baseDate);
	 			vo.ENDDA = new Date(baseDate);
	 			view.reqList.addItem(vo);
			}
 		}

 		private function addRecord():void
 		{
 			var vo:ReqVacationVO = new ReqVacationVO();
 			vo.selectedIndex = 0;
 			vo.BEGDA = new Date(baseDate);
 			vo.ENDDA = new Date(baseDate);
 			view.reqList.addItem(vo);
 		}
 		
		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Utility Functions
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
        private function get view():ModWorkTimeView
        {
            return viewComponent as ModWorkTimeView;
        }
	}
}